package com.chj.comp.common.rabbitmq.queue;

import com.chj.comp.common.rabbitmq.sender.MqFanoutSender;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 *
 * @Description: 发布订阅模型（Fanout广播类型，一个消息被所有消费者消费）：
 * 交换机会将接收到的消息路由到每一个跟其绑定的queue
 *
 *                / 队列1 - 消费者1
 * 生产者 - 交换机
 *               \ 队列2 - 消费者2
 *
 * @author cuihui
 * @date 2022-06-11
 *
 */
@Configuration
public class MqFanoutQueue {
    @Resource
    private RabbitTemplate rabbitTemplate;

    public static final String EXCHANGE_NAME = "mq.fanout.exchange";
    public static final String QUEUE_NAME1 = "mq.fanout.queue1";
    public static final String QUEUE_NAME2 = "mq.fanout.queue2";

    /**
     * 定义交换机
     * @return
     */
    @Bean(name = "mqFanoutExchange")
    public FanoutExchange mqFanoutExchange() {
        return ExchangeBuilder.fanoutExchange(EXCHANGE_NAME).build();
    }

    /**
     * 定义队列1
     * @return
     */
    @Bean(name = "mqFanoutQueue1")
    public Queue mqFanoutQueue1() {
        return QueueBuilder.durable(QUEUE_NAME1).build();
    }

    /**
     * 定义队列2
     * @return
     */
    @Bean(name = "mqFanoutQueue2")
    public Queue mqFanoutQueue2() {
        return QueueBuilder.durable(QUEUE_NAME2).build();
    }

    /**
     * 绑定队列1到交换机
     * @return
     */
    @Bean
    public Binding mqFanoutQueue1Binding(@Qualifier("mqFanoutQueue1") Queue mqFanoutQueue1,
                                         @Qualifier("mqFanoutExchange") FanoutExchange mqFanoutExchange) {
        return BindingBuilder
                .bind(mqFanoutQueue1)
                .to(mqFanoutExchange);
    }

    /**
     * 绑定队列2到交换机
     * @return
     */
    @Bean
    public Binding mqFanoutQueue2Binding(@Qualifier("mqFanoutQueue2") Queue mqFanoutQueue2,
                                         @Qualifier("mqFanoutExchange") FanoutExchange mqFanoutExchange) {
        return BindingBuilder
                .bind(mqFanoutQueue2)
                .to(mqFanoutExchange);
    }

    @Bean
    public MqFanoutSender mqFanoutSender() {
        return new MqFanoutSender(rabbitTemplate);
    }
}
